package org.atlantis.net.base.vote;

import java.io.DataInputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.atlantis.net.base.frame.Framer;
import org.atlantis.net.base.frame.LengthFramer;

/*
 * 投票客户端。
 */
public class VoteClientTCP {

	public static final int CANDIDATEID = 888;
	public static final String SERVER_HOST = "172.19.5.92";
	public static final int SERVER_PORT = 10006;

	public static void main(String[] args) throws Exception {
		Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
		OutputStream out = socket.getOutputStream();

		VoteMessageCoder coder = new VoteMessageBinCoder();
		Framer framer = new LengthFramer(new DataInputStream(
				socket.getInputStream()));

		// 发送查询请求
		VoteMessage message = new VoteMessage(false, true, CANDIDATEID, 0);
		byte[] encodedMessage = coder.encode(message);
		System.out.println("Sending Inquiry (" + encodedMessage.length
				+ " bytes): ");
		framer.frameMessage(encodedMessage, out);

		// 发送投票请求
		message.setInquiry(false);
		encodedMessage = coder.encode(message);
		framer.frameMessage(encodedMessage, out);
		System.out.println("Sending Inquiry (" + encodedMessage.length
				+ " bytes): ");
		
		// 接收服务器的请求回执信息
		encodedMessage = framer.nextMessage();
		message = coder.decode(encodedMessage);
		System.out.println("Received response (" + encodedMessage.length + " bytes)");
		System.out.println(message);
		
		// 接收服务器的投票回执信息
		encodedMessage = framer.nextMessage();
		message = coder.decode(encodedMessage);
		System.out.println("Received response (" + encodedMessage.length + " bytes)");
		System.out.println(message);
		
		socket.close();
	}
}
